import React, { useEffect, useRef, useState } from "react"

interface TextStreamProps{
   text:string
   style?:React.CSSProperties,
   className?:string
   speed?:number
   onEnd?:()=>any
}
const TextStream = ({onEnd,text,className,style,speed=90}:TextStreamProps)=>{
const [str,setStr] = useState('');
const indexRef = useRef<number>(0)
const nextStr = ()=>{
    const index = indexRef.current
    const s =  text.substring(index,index+1);
    setStr(str=>str+s)
    if(index<text.length){
        indexRef.current = indexRef.current+1;
        setTimeout(nextStr,speed)
    }else{
        onEnd&&onEnd()
    }
   
}
useEffect(()=>{
    if(text){
        setStr('');
        indexRef.current = 0
         nextStr()  
    }
      
},[text])
return <div style={style} className={className}  dangerouslySetInnerHTML={{
    __html:str
}}></div>
}
export default TextStream